package com.fc.advbox.service.impl;

import com.fc.advbox.dao.*;
import com.fc.advbox.dto.user.AdvUserReqDto;
import com.fc.advbox.entity.AdvUserEntity;
import com.fc.advbox.entity.InvestorAcctEntity;
import com.fc.advbox.entity.RoleEntity;
import com.fc.advbox.entity.UserTokenAcctEntity;
import com.fc.advbox.service.IOrgAcctService;
import com.fc.advbox.service.IUserService;
import com.fc.advbox.utils.Constant;
import com.fc.advbox.utils.DateTimeHelper;
import com.fc.advbox.utils.RRException;
import com.fc.advbox.utils.validator.Assert;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

@Service("userService")
public class UserServiceImpl implements IUserService {
	@Autowired
	private UserDao userDao;

	@Autowired
	private RoleDao roleDao;

	@Autowired
	private UserRoleDao userRoleDao;

	@Autowired
    private InvestorAcctDao investorAcctDao;

	@Autowired
	private OrgDao orgDao;

	@Autowired
	private IOrgAcctService orgAcctService;

	@Autowired
	private UserTokenAcctDao userTokenAcctDao;

	@Override
	public AdvUserEntity queryObject(Long userId){
		return userDao.queryObject(userId);
	}

	public AdvUserEntity queryByUserName(String name){ return userDao.queryByUserName(name);}

	@Override
	public List<AdvUserEntity> queryList(Map<String, Object> map){

		return userDao.queryList(map);
	}
	@Override
	public int queryTotal(Map<String, Object> map){
		return userDao.queryTotal(map);
	}
	
	@Override
	public void save(String mobile, String password){
		AdvUserEntity user = new AdvUserEntity();
		user.setPhone(mobile);
		user.setName(mobile);
		user.setPassword(DigestUtils.sha256Hex(password));
		user.setCreateTime(new Date());
		userDao.save(user);
	}

	@Override
	@Transactional
	public void save(AdvUserReqDto user) {
		// 通过电话号码查询，确认该号码是否被注册
		AdvUserEntity userEntity = userDao.queryByPhone(user.getPhone());
		if(userEntity != null)
		{
			throw new RRException("该手机号已注册, 请更换手机号码!");
		}
		if(Constant.UserType.INVESTOR.getValue() == Integer.valueOf(user.getType())){
			if(null == user.getRealName() || "".equals(user.getRealName()) ){
				throw new RRException("投资者用户需要填写真实姓名!");
			}
		}else{
			if(null == user.getOrgId() || "".equals(user.getOrgId())){
				throw new RRException("机构用户需要填写机构ID!");
			}else{
				Integer orgId = Integer.valueOf(user.getOrgId());
				if(null ==orgDao.queryObject(orgId)){
					throw new RRException("机构ID不正确!");
				}
			}
		}

		AdvUserEntity entity = new AdvUserEntity();
		entity.setPassword(new Sha256Hash(user.getPassword()).toHex());
		entity.setStatus(Constant.Status.ENABLE.getValue());
		entity.setName(user.getName());
		entity.setNickName(user.getRealName());
		entity.setPhone(user.getPhone());
		entity.setAvatar(user.getAvatar());
		entity.setCreateTime(new Date());
		entity.setUpdateTime(new Date());
		entity.setDeviceUUID(user.getDeviceUUID());
		entity.setEmail(user.getEmail());
		entity.setOpenId(user.getOpenId());
		entity.setDeviceUUID(user.getDeviceUUID());
		entity.setType(user.getType());
		if(user.getOrgId() != null && !"".equals(user.getOrgId()) ){
			entity.setOrgId(Long.valueOf(user.getOrgId()));
		}

		// 添加新用户，插入一条新数据
		userDao.save(entity);

        //保存用户与角色关系
		if(entity.getId() != 0)
		{
            RoleEntity roleEntity = getRoleByUserType(entity);
			List<Long> roleIdList = new ArrayList<>();
			roleIdList.add(roleEntity.getId());

			Map<String, Object> paramMap = new HashMap<>();
			paramMap.put("userId", entity.getId());
			paramMap.put("roleIdList", roleIdList);
			userRoleDao.save(paramMap);
		}

		//创建投资者资产账户
        if(entity.getId() != 0)
        {
            if (Integer.valueOf(user.getType()) == Constant.UserType.INVESTOR.getValue()){
                InvestorAcctEntity investorAcctEntity = new InvestorAcctEntity();
                investorAcctEntity.setBalance(new BigDecimal(0));
                investorAcctEntity.setUserId(entity.getId());
				investorAcctEntity.setRealName(user.getRealName());
				investorAcctEntity.setIdCard(user.getIdCard());
                investorAcctEntity.setProfit(new BigDecimal(0));
				investorAcctEntity.setStatus(Constant.Status.ENABLE.getValue());
				investorAcctEntity.setCreateTime(new Date());
				investorAcctEntity.setExpireTime(DateTimeHelper.getDateFromString("2030-12-30", DateTimeHelper.PAYLOAD_DATEONLY));
				investorAcctEntity.setType(Constant.AcctType.CASH.getValue());
				investorAcctEntity.setAcctNum(""+investorAcctEntity.hashCode());
				investorAcctDao.save(investorAcctEntity);
            }
        }

        //创建投资者虚拟币账户
		if(entity.getId() != 0
				&& Constant.UserType.INVESTOR.getValue().equals(Integer.valueOf(user.getType())))
		{
			UserTokenAcctEntity tokenAcctEntity = new UserTokenAcctEntity();
			tokenAcctEntity.setUserId(entity.getId());
			tokenAcctEntity.setAccountName(entity.getNickName()+"的虚拟币账户");
			tokenAcctEntity.setAccountType(Constant.TokenAccountType.KEY.getValue());
			tokenAcctEntity.setStatus(Constant.Status.ENABLE.getValue());
			tokenAcctEntity.setCreateTime(new Date());
			userTokenAcctDao.save(tokenAcctEntity);
		}
	}

	private RoleEntity getRoleByUserType(AdvUserEntity user){
        RoleEntity role = new RoleEntity();
        if (Integer.valueOf(user.getType()) == Constant.UserType.OWNER.getValue()){
            role = roleDao.queryRoleByName(Constant.UserType.OWNER.getRoleName());
        }else if (Integer.valueOf(user.getType()) == Constant.UserType.AGENT.getValue()){
            role = roleDao.queryRoleByName(Constant.UserType.CHANNEL.getRoleName());
        }else if (Integer.valueOf(user.getType()) == Constant.UserType.CHANNEL.getValue()){
            role = roleDao.queryRoleByName(Constant.UserType.RENT.getRoleName());
        }else if (Integer.valueOf(user.getType()) == Constant.UserType.RENT.getValue()){
            role = roleDao.queryRoleByName(Constant.UserType.RENT.getRoleName());
        }else if (Integer.valueOf(user.getType()) == Constant.UserType.INVESTOR.getValue()){
            role = roleDao.queryRoleByName(Constant.UserType.INVESTOR.getRoleName());
        }
        return role;
    }

	@Override
	public void update(AdvUserEntity user){
		userDao.update(user);
	}
	
	@Override
	public void delete(Long userId){
		userDao.delete(userId);
	}
	
	@Override
	public void deleteBatch(Long[] userIds){
		userDao.deleteBatch(userIds);
	}

	@Override
	public AdvUserEntity queryByMobile(String mobile) {
		return userDao.queryByPhone(mobile);
	}

	@Override
	public long login(String mobile, String password) {
		AdvUserEntity user = queryByMobile(mobile);
		Assert.isNull(user, "手机号或密码错误");
		String shaPwd = DigestUtils.sha256Hex(password);
		if(!user.getPassword().equals(DigestUtils.sha256Hex(password))){
			throw new RRException("手机号或密码错误");
		}
		return user.getId();
	}

	@Override
	public int updatePassword(Long userId, String oldPwd, String newPwd){
     	AdvUserEntity user = userDao.queryObject(userId);
		if(user == null)
		{
			throw new RRException("无法获取用户信息");
		}

		if(!user.getPassword().equals(oldPwd))
		{
			throw new RRException("原密码不匹配");
		}

		Map<String, Object> map = new HashMap<>();
		map.put("userId", userId);
		map.put("password", oldPwd);
		map.put("newPassword", newPwd);
		return userDao.updatePassword(map);
	}

	public AdvUserEntity queryDetailInfoById(Long userId){
		if(userId == null)
		{
			return null;
		}

		// 用户基本信息
		AdvUserEntity advUserEntity = userDao.queryObject(userId);
		if(advUserEntity == null)
		{
			throw new RRException("为获取到用户信息信息");
		}

		// 获取用户所属的角色列表
		List<Long> roleIdList = userRoleDao.queryRoleIdList(userId);
		advUserEntity.setRoleIdList(roleIdList);

		// 所属组织信息
		if(advUserEntity.getOrgId() != null)
		{
			advUserEntity.setOrganization(orgDao.queryObject(advUserEntity.getOrgId()));
		}

		// 所属组织账号信息
		if(advUserEntity.getOrgId() != null)
		{
			advUserEntity.setOrgAccount(orgAcctService.queryByOrgId(advUserEntity.getOrgId()));
		}
		return advUserEntity;
	}
}
